package jrpc

import (
	"log"
	"net"
	"net/http"
	"os"

	"github.com/osamingo/jsonrpc/v2"
)

var s = NewServer("/tmp/my_rpc.sock")

type Server struct {
	addr string
	mr   *jsonrpc.MethodRepository
}

type Handler interface {
	Name() string
	jsonrpc.Handler
	Params() any
	Result() any
}

func Register(handler Handler) error {
	return s.Register(handler.Name(), handler)
}

func Start() error { return s.Start() }

func NewServer(address string) *Server {
	mr := jsonrpc.NewMethodRepository()
	return &Server{
		mr:   mr,
		addr: address,
	}
}

func (s *Server) Register(name string, handler Handler) error {
	return s.mr.RegisterMethod(name, handler, handler.Params(), handler.Result())
}

func (s *Server) Start() error {
	socketPath := s.addr
	os.Remove(socketPath) // 删除之前可能存在的套接字文件
	// 监听 Unix 域套接字
	listener, err := net.Listen("unix", socketPath)
	if err != nil {
		log.Fatalln("Failed to listen on Unix socket:", err)
	}
	defer listener.Close()

	http.Handle("/rpc", s.mr)
	http.HandleFunc("/rpc/debug", s.mr.ServeDebug)

	if err := http.Serve(listener, http.DefaultServeMux); err != nil {
		return err
	}
	return nil
}
